const tenantController = require('../controllers/tenantController');
const { authenticate, requireRole } = require('../middleware/auth');
const { identifyTenant, requireTenant } = require('../middleware/tenant');

async function tenantRoutes(fastify, options) {
  // 应用租户识别中间件到所有路由
  fastify.addHook('preHandler', identifyTenant);
  
  // 系统管理员路由 - 管理所有租户
  
  // 创建租户
  fastify.post('/', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Create a new tenant (System Admin only)',
      tags: ['Tenant Management'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      body: {
        type: 'object',
        required: ['name', 'domain', 'email'],
        properties: {
          name: { 
            type: 'string', 
            minLength: 1, 
            maxLength: 100,
            description: 'Tenant name'
          },
          domain: { 
            type: 'string', 
            minLength: 3, 
            maxLength: 63,
            pattern: '^[a-z0-9-]+$',
            description: 'Tenant domain (lowercase, alphanumeric and hyphens only)'
          },
          email: { 
            type: 'string', 
            format: 'email',
            description: 'Tenant contact email'
          },
          adminUser: {
            type: 'object',
            properties: {
              email: { 
                type: 'string', 
                format: 'email',
                description: 'Admin user email'
              },
              password: { 
                type: 'string', 
                minLength: 8,
                description: 'Admin user password'
              },
              firstName: { 
                type: 'string', 
                minLength: 1, 
                maxLength: 50,
                description: 'Admin user first name'
              },
              lastName: { 
                type: 'string', 
                minLength: 1, 
                maxLength: 50,
                description: 'Admin user last name'
              }
            },
            description: 'Optional admin user to create with the tenant'
          }
        }
      },
      response: {
        201: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                tenant: {
                  type: 'object',
                  properties: {
                    id: { type: 'string' },
                    tenantId: { type: 'string' },
                    name: { type: 'string' },
                    domain: { type: 'string' },
                    email: { type: 'string' },
                    status: { type: 'string' },
                    plan: { type: 'string' }
                  }
                },
                adminUser: {
                  type: 'object',
                  nullable: true
                }
              }
            },
            message: { type: 'string' }
          }
        }
      }
    }
  }, tenantController.createTenant);
  
  // 获取租户列表
  fastify.get('/', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Get list of tenants (System Admin only)',
      tags: ['Tenant Management'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      querystring: {
        type: 'object',
        properties: {
          page: { 
            type: 'integer', 
            minimum: 1, 
            default: 1,
            description: 'Page number'
          },
          limit: { 
            type: 'integer', 
            minimum: 1, 
            maximum: 100, 
            default: 20,
            description: 'Items per page'
          },
          status: { 
            type: 'string', 
            enum: ['active', 'inactive', 'suspended'],
            description: 'Filter by status'
          },
          plan: { 
            type: 'string', 
            enum: ['free', 'basic', 'premium', 'enterprise'],
            description: 'Filter by plan'
          },
          search: { 
            type: 'string',
            description: 'Search in name, domain, or email'
          },
          sortBy: { 
            type: 'string', 
            default: 'createdAt',
            description: 'Sort field'
          },
          sortOrder: { 
            type: 'string', 
            enum: ['asc', 'desc'], 
            default: 'desc',
            description: 'Sort order'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                tenants: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      id: { type: 'string' },
                      tenantId: { type: 'string' },
                      name: { type: 'string' },
                      domain: { type: 'string' },
                      email: { type: 'string' },
                      status: { type: 'string' },
                      plan: { type: 'string' },
                      createdAt: { type: 'string' }
                    }
                  }
                },
                pagination: {
                  type: 'object',
                  properties: {
                    page: { type: 'integer' },
                    limit: { type: 'integer' },
                    total: { type: 'integer' },
                    pages: { type: 'integer' }
                  }
                }
              }
            },
            message: { type: 'string' }
          }
        }
      }
    }
  }, tenantController.getTenants);
  
  // 获取租户详情
  fastify.get('/:tenantId', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Get tenant details (System Admin only)',
      tags: ['Tenant Management'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      params: {
        type: 'object',
        required: ['tenantId'],
        properties: {
          tenantId: { 
            type: 'string',
            description: 'Tenant ID'
          }
        }
      }
    }
  }, tenantController.getTenant);
  
  // 更新租户信息
  fastify.put('/:tenantId', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Update tenant information (System Admin only)',
      tags: ['Tenant Management'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      params: {
        type: 'object',
        required: ['tenantId'],
        properties: {
          tenantId: { 
            type: 'string',
            description: 'Tenant ID'
          }
        }
      },
      body: {
        type: 'object',
        properties: {
          name: { 
            type: 'string', 
            minLength: 1, 
            maxLength: 100,
            description: 'Tenant name'
          },
          domain: { 
            type: 'string', 
            minLength: 3, 
            maxLength: 63,
            pattern: '^[a-z0-9-]+$',
            description: 'Tenant domain'
          },
          email: { 
            type: 'string', 
            format: 'email',
            description: 'Tenant contact email'
          },
          status: { 
            type: 'string', 
            enum: ['active', 'inactive', 'suspended'],
            description: 'Tenant status'
          },
          plan: { 
            type: 'string', 
            enum: ['free', 'basic', 'premium', 'enterprise'],
            description: 'Tenant plan'
          }
        }
      }
    }
  }, tenantController.updateTenant);
  
  // 删除租户
  fastify.delete('/:tenantId', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Delete tenant (System Admin only)',
      tags: ['Tenant Management'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      params: {
        type: 'object',
        required: ['tenantId'],
        properties: {
          tenantId: { 
            type: 'string',
            description: 'Tenant ID'
          }
        }
      }
    }
  }, tenantController.deleteTenant);
  
  // 激活租户
  fastify.post('/:tenantId/activate', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Activate tenant (System Admin only)',
      tags: ['Tenant Management'],
      params: {
        type: 'object',
        required: ['tenantId'],
        properties: {
          tenantId: { 
            type: 'string',
            description: 'Tenant ID'
          }
        }
      }
    }
  }, tenantController.activateTenant);
  
  // 停用租户
  fastify.post('/:tenantId/deactivate', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Deactivate tenant (System Admin only)',
      tags: ['Tenant Management'],
      params: {
        type: 'object',
        required: ['tenantId'],
        properties: {
          tenantId: { 
            type: 'string',
            description: 'Tenant ID'
          }
        }
      }
    }
  }, tenantController.deactivateTenant);
  
  // 暂停租户
  fastify.post('/:tenantId/suspend', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Suspend tenant (System Admin only)',
      tags: ['Tenant Management'],
      params: {
        type: 'object',
        required: ['tenantId'],
        properties: {
          tenantId: { 
            type: 'string',
            description: 'Tenant ID'
          }
        }
      },
      body: {
        type: 'object',
        properties: {
          reason: { 
            type: 'string', 
            maxLength: 500,
            description: 'Suspension reason'
          }
        }
      }
    }
  }, tenantController.suspendTenant);
  
  // 获取租户统计信息
  fastify.get('/:tenantId/stats', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Get tenant statistics (System Admin only)',
      tags: ['Tenant Management'],
      params: {
        type: 'object',
        required: ['tenantId'],
        properties: {
          tenantId: { 
            type: 'string',
            description: 'Tenant ID'
          }
        }
      }
    }
  }, tenantController.getTenantStats);
  
  // 更新租户订阅
  fastify.put('/:tenantId/subscription', {
    preHandler: [authenticate, requireRole('system_admin')],
    schema: {
      description: 'Update tenant subscription (System Admin only)',
      tags: ['Tenant Management'],
      params: {
        type: 'object',
        required: ['tenantId'],
        properties: {
          tenantId: { 
            type: 'string',
            description: 'Tenant ID'
          }
        }
      },
      body: {
        type: 'object',
        properties: {
          startDate: { 
            type: 'string', 
            format: 'date',
            description: 'Subscription start date'
          },
          endDate: { 
            type: 'string', 
            format: 'date',
            description: 'Subscription end date'
          },
          autoRenew: { 
            type: 'boolean',
            description: 'Auto-renewal setting'
          },
          paymentMethod: { 
            type: 'string',
            description: 'Payment method'
          }
        }
      }
    }
  }, tenantController.updateSubscription);
  
  // 检查域名可用性
  fastify.post('/check-domain', {
    schema: {
      description: 'Check domain availability',
      tags: ['Tenant Management'],
      body: {
        type: 'object',
        required: ['domain'],
        properties: {
          domain: { 
            type: 'string', 
            minLength: 3, 
            maxLength: 63,
            pattern: '^[a-z0-9-]+$',
            description: 'Domain to check'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                available: { type: 'boolean' },
                domain: { type: 'string' },
                reason: { type: 'string', nullable: true }
              }
            },
            message: { type: 'string' }
          }
        }
      }
    }
  }, tenantController.checkDomainAvailability);
  
  // 租户用户路由 - 管理当前租户
  
  // 获取当前租户信息
  fastify.get('/current', {
    preHandler: [authenticate, requireTenant],
    schema: {
      description: 'Get current tenant information',
      tags: ['Current Tenant'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      }
    }
  }, tenantController.getCurrentTenant);
  
  // 更新当前租户设置
  fastify.put('/current/settings', {
    preHandler: [authenticate, requireTenant, requireRole('admin')],
    schema: {
      description: 'Update current tenant settings (Tenant Admin only)',
      tags: ['Current Tenant'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      body: {
        type: 'object',
        properties: {
          theme: { 
            type: 'string', 
            enum: ['light', 'dark', 'auto'],
            description: 'UI theme'
          },
          language: { 
            type: 'string', 
            minLength: 2, 
            maxLength: 5,
            description: 'Language code'
          },
          timezone: { 
            type: 'string',
            description: 'Timezone'
          },
          features: {
            type: 'object',
            patternProperties: {
              ".*": { type: 'boolean' }
            },
            description: 'Feature toggles'
          },
          limits: {
            type: 'object',
            properties: {
              users: { 
                type: 'integer', 
                minimum: 1,
                description: 'Maximum number of users'
              },
              storage: { 
                type: 'integer', 
                minimum: 1,
                description: 'Storage limit in MB'
              },
              apiCalls: { 
                type: 'integer', 
                minimum: 1,
                description: 'API calls limit per month'
              }
            },
            description: 'Usage limits'
          }
        }
      }
    }
  }, tenantController.updateCurrentTenantSettings);
  
  // 获取当前租户功能使用情况
  fastify.get('/current/usage', {
    preHandler: [authenticate, requireTenant],
    schema: {
      description: 'Get current tenant feature usage',
      tags: ['Current Tenant'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      }
    }
  }, async (request, reply) => {
    return tenantController.getFeatureUsage(request, reply);
  });
}

module.exports = tenantRoutes;